package org.ilc.sample.util;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.ilc.push.Message;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author : malongbo
 * Date: 13-4-12
 * Time: 上午10:10
 */
public class BeanUtil {

    /**
     *
     * @param bean
     * @return
     * @throws java.beans.IntrospectionException
     */
    public static DBObject bean2DBObject (Object bean) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        BeanInfo beanInfo = null;

        beanInfo = Introspector.getBeanInfo(bean.getClass());

        if (beanInfo != null) {
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            DBObject dbObject = new BasicDBObject();
            for (PropertyDescriptor pd : pds) {
                String propertyName = pd.getName();
                if (propertyName.equals("class")) continue;

                Method method = pd.getReadMethod();

                Object object = method.invoke(bean);
                dbObject.put(propertyName, object);
            }
            return dbObject;
        }
        return null;
    }

    /**
     *
     * @param dbObject
     * @return
     */
    public static Message DBObject2Message (DBObject dbObject) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        BeanInfo beanInfo = null;
        Message msg = new Message ();

        beanInfo = Introspector.getBeanInfo(Message.class);

        if (beanInfo != null && dbObject != null) {
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor pd : pds) {
                String propertyName = pd.getName();
                if (propertyName.equals("class")) continue;

                Method method = pd.getWriteMethod();
                Object value = dbObject.get(propertyName);

                if (method != null && value != null)
                    method.invoke(msg, value);
            }
            return msg;
        }
        return null;
    }
}
